package com.ruoyi.flowable.listener;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysDocument;
import com.ruoyi.common.utils.ExcelMergerUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.onlyOffice.domain.CheckFormInfo;
import com.ruoyi.onlyOffice.domain.FileUpload;
import com.ruoyi.onlyOffice.service.FileUploadService;
import com.ruoyi.system.service.ISysDocumentService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.HistoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 执行监听器
 *
 * 执行监听器允许在执行过程中执行Java代码。
 * 执行监听器可以捕获事件的类型：
 * 流程实例启动，结束
 * 输出流捕获
 * 获取启动，结束
 * 路由开始，结束
 * 中间事件开始，结束
 * 触发开始事件，触发结束事件
 *
 * @author Tony
 * @date 2022/12/16
 */
@Slf4j
@Component
public class FlowExecutionListener implements ExecutionListener {
    /**
     * 流程设计器添加的参数
     */
    private Expression param;
    private static HistoryService historyService;
    private static FileUploadService fileUploadService;
    private static ISysDocumentService documentService;

    @Autowired
    public void setHistoryService(HistoryService historyService) {
        FlowExecutionListener.historyService = historyService;
    }

    @Autowired
    public void setFileUploadService(FileUploadService fileUploadService) {
        FlowExecutionListener.fileUploadService = fileUploadService;
    }

    @Autowired
    public void setDocumentService(ISysDocumentService documentService) {
        FlowExecutionListener.documentService = documentService;
    }

    @Override
    public void notify(DelegateExecution execution) {
        log.info("执行监听器:{}", execution);
        String insId = execution.getProcessInstanceId();
        List<HistoricTaskInstance> historicTaskInstance = historyService.createHistoricTaskInstanceQuery().processInstanceId(insId).orderByHistoricTaskInstanceStartTime().asc().list();
        String firstTaskId = historicTaskInstance.get(0).getId();
        List<CheckFormInfo> formList = fileUploadService.selectFormList(firstTaskId);
        List<String> excel = new ArrayList<>();
        String templateKey = "";
        for (CheckFormInfo formInfo:formList) {
            if("file-upload".equals(formInfo.getFieldType())){
                templateKey = formInfo.getFieldKey();
            }
        }
        String templateFile = "";
        String mergeExcelName = "";
        Long userId=1L;
        List<FileUpload> fileList = fileUploadService.queryFileList(insId,null,null);
        for (FileUpload fileInfo:fileList) {
            String fileUrl = fileInfo.getFilePath() + fileInfo.getFileName();
            excel.add(fileUrl);
            if(templateKey.equals(fileInfo.getFieldKey())){
                templateFile = fileUrl;
                mergeExcelName = fileInfo.getFilePath() + "Merge" + fileInfo.getFileName();
                userId = fileInfo.getUserId();
            }
        }
        /*List<String> excel = new ArrayList<>();
        String templateFile = "D:\\ruoyi\\uploadPath\\upload\\2025\\04\\10\\cfxps报文域配置模版.xlsx";
        excel.add(templateFile);
        excel.add("D:\\ruoyi\\uploadPath\\upload\\2025\\04\\10\\cfxps报文域配置_20250410163525A001.xlsx");
        excel.add("D:\\ruoyi\\uploadPath\\upload\\2025\\04\\10\\cfxps报文域配置-xxx_20250410163646A002.xlsx");
        String mergeExcelName = "D:\\ruoyi\\uploadPath\\upload\\2025\\04\\10\\mergeExcel.xlsx";*/
        try {
            ExcelMergerUtil.mergeExcelFiles(excel,templateFile,mergeExcelName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        FileUpload upload = new FileUpload();
        upload.setUploadDate(new Date());
        upload.setFileType(mergeExcelName.substring(mergeExcelName.indexOf(".")));
        upload.setFilePath(mergeExcelName.substring(0,mergeExcelName.lastIndexOf("/")));
        upload.setFileName(mergeExcelName.substring(mergeExcelName.lastIndexOf("/")));
        upload.setTaskId(insId);
        upload.setFieldKey(null);
        fileUploadService.saveFile(upload);

        SysDocument document = new SysDocument();
        document.setDocumentType(upload.getFileType());
        document.setCategoryId(2L);
        document.setDocumentName(upload.getFileName());
        document.setFilePath(upload.getFilePath().replace(RuoYiConfig.getProfile(),"/profile/"));
        document.setCreateBy(userId.toString());
        documentService.insertDocument(document);
    }
}
